package com.zh.config.dialog

import android.app.Dialog
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.zh.common.R
import com.zh.config.db.DownEnum
import com.zh.config.db.DownloadDao
import com.zh.common.utils.EmptyUtils
import com.zh.config.PerConfig
import com.zh.config.ZjConfig
import com.zh.config.utils.DownloadFileUtils
import com.zh.config.utils.KnowledgeType
import com.zh.config.utils.VideoCache
import java.io.File

class DownloadDialog(context: Context) : Dialog(context, R.style.custom_dialog2) {

    private var downloadDao: DownloadDao? = null
    private val iAdapter by lazy { DownloadAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_download)

        val tvCancel = findViewById<TextView>(R.id.tvCancel)
        tvCancel.setOnClickListener { dismiss() }

        val recycler = findViewById<RecyclerView>(R.id.recycler)
        recycler.adapter = iAdapter
        downloadDao?.let {
            iAdapter.setNewInstance(mutableListOf(it))
        }
    }

    fun showDialog(url: String, logo: String = "", fileName: String? = "", fileSize: Int = -1) {
        if (EmptyUtils.isNotEmpty(url)) {
            PermissionUtils.permission(*PerConfig.sdcard.toTypedArray())
                .callback { isAllGranted, _, _, _ ->
                    if (isAllGranted) {
                        showUI(url, logo, fileName, fileSize)
                    }
                }.request()
        }
    }

    private fun showUI(url: String, logo: String = "", file_Name: String? = "", fileSize: Int = -1) {
        var fileName = if (EmptyUtils.isNotEmpty(file_Name)) {
            file_Name!!
        } else {
            val name = Uri.parse(url).lastPathSegment
                ?: url.substring(url.lastIndexOf("/") + 1).split("?")[0]
            if (KnowledgeType.isDownloadFile(name)) {
                name
            } else {
                val newUrl = url.substring(url.lastIndexOf("/") + 1)
                if (newUrl.contains("%2F")) {
                    newUrl.substring(newUrl.lastIndexOf("%2F") + 3)
                } else {
                    newUrl
                }
            }
        }
        val file = ZjConfig.downloadPath
        if (!file.exists()) file.mkdirs()
        var filePath = File(file, fileName)
        if (!filePath.exists()) {
            try {
                val succ = filePath.createNewFile()
                if (!succ) {
                    val sux = fileName.substring(fileName.lastIndexOf("."))
                    if (fileName.contains("_")) {
                        fileName = fileName.substring(0, fileName.indexOf("_")) + sux
                    } else if (fileName.contains("-")) {
                        fileName = fileName.substring(0, fileName.indexOf("-")) + sux
                    }
                    fileName = fileName.lowercase()
                    filePath = File(file, fileName)
                    if (!filePath.exists()) {
                        filePath.createNewFile()
                    }
                    if (!filePath.exists()) {
                        filePath.createNewFile()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        downloadDao =
            DownloadFileUtils.instance.dbDownloadHelper.getDownload(url)
        if (downloadDao == null) {
            if (filePath.exists() && filePath.length() > 0L) {
                getExistsFile(url, fileName, logo, filePath, 1, fileSize)
            } else {
                LogUtils.d("文件不存在: $fileName")
                if (fileSize != -1) {
                    showDlg(url, fileName, logo, filePath.absolutePath, fileSize)
                } else {
                    VideoCache().startDownload(url) {
                        showDlg(url, fileName, logo, filePath.absolutePath, it)
                    }
                }
            }
        } else {
            LogUtils.d("直接打开下载dialog: $fileName")
            super.show()
        }
    }

    private fun getExistsFile(
        url: String, fileName: String, logo: String, filePath: File, index: Int, fileSize: Int = -1
    ) {
        try {
            LogUtils.d("重命名文件: $fileName")
            val nameSplit = filePath.name.split(".")
            val name = if (nameSplit[0].contains("(${index - 1})")) {
                nameSplit[0].substring(0, nameSplit[0].indexOf("(${index - 1})"))
            } else {
                nameSplit[0]
            }
            val file = if (nameSplit.size > 1)
                File(ZjConfig.downloadPath, name + "(${index})." + nameSplit[1])
            else File(ZjConfig.downloadPath, name + "(${index})")
            if (file.exists() && filePath.length() > 0L) {
                getExistsFile(url, file.name, logo, file, index + 1, fileSize)
            } else {
                if (fileSize != -1) {
                    showDlg(url, file.name, logo, file.absolutePath, fileSize)
                } else {
                    VideoCache().startDownload(url) {
                        showDlg(url, file.name, logo, file.absolutePath, it)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun showDlg(url: String, fileName: String, logo: String, filePath: String, fileSize: Int) {
        downloadDao = DownloadDao(
            0, url, fileName, logo, filePath, DownEnum.pending.state,
            fileSize,
            (System.currentTimeMillis() / 1000).toInt()
        )
        super.show()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        window?.apply {
            setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            setWindowAnimations(android.R.style.Animation_InputMethod)
            setGravity(Gravity.BOTTOM)
        }
    }
}